#import "SearchSubHeader.h"
#import "RNConstants.h"

@implementation SearchSubHeader

@synthesize controller = controller_;
@synthesize filterPredicateTemplate = filterPredicateTemplate_;
@synthesize displayIndex = displayIndex_;
@synthesize objectDictionary = objectDictionary_;

-(id)initWithController:(NSArrayController *)theController {
    if (!(self = [super init]))
        return nil;
    
    [self setController:theController];
    NSString *title = [theController entityName];
    if ([title isEqualToString:RNEntityNameCategory])
        title = @"Categories";
    else {
        title = [title substringFromIndex:2];
        title = [NSString stringWithFormat:@"%@s", title];
    }
    [self setObjectDictionary:[NSDictionary dictionaryWithObject:title forKey:RNTitleKey]];
    
    return self;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    // Only observing controller's arrangedObjects.  This is a hack because NSArrayController's arrangedObjects won't let you use +keyPathsForValuesAffecting...
    [self willChangeValueForKey:@"children"];
    [self didChangeValueForKey:@"children"];
}

-(NSArray *)children {
    return [[self controller] arrangedObjects];
}

-(void)updateFilterWithString:(NSString *)filterString {
    NSDictionary *filterVariables = [NSDictionary dictionaryWithObject:filterString forKey:@"FILTER_STRING"];
    [[self controller] setFilterPredicate:[[self filterPredicateTemplate] predicateWithSubstitutionVariables:filterVariables]];
}

@end
